from flask import Blueprint,render_template,jsonify,redirect,url_for
import sys
sys.path.append("..")
from exts import mail,db
from flask_mail import Message
from flask import request
import random
import string
from models import EmailCaptchaModel,UserModel
from .forms import RegisterForm
from werkzeug.security import generate_password_hash


# 创建蓝图
bp=Blueprint("auth",__name__,url_prefix="/auth")

@bp.route('/login')
def login():
    return render_template('login.html')

@bp.route('/register',methods=['GET','POST'])
def register():
    if request.method=='GET':
        return render_template('register.html')
    else:
        # 验证用户提交的邮箱和验证码是否正确
        form=RegisterForm(request.form)
        if form.validate():
            email=form.email.data
            username=form.username.data
            password=form.password.data
            user=UserModel(email=email,username=username,password=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('auth.login'))
        else:
            print(form.errors)
            return redirect(url_for('auth.register'))

@bp.route('/captcha/email')
def get_email__captcha():
    email=request.args.get('email')
    source=string.digits*4
    captcha=random.sample(source,4)
    captcha="".join(captcha)
    message=Message(subject="知了传课注册验证码",recipients=[email],body=f"您的验证码是：{captcha}")
    mail.send(message)
    # 用数据库保存验证码
    email_captcha=EmailCaptchaModel(email=email,captcha=captcha)
    db.session.add(email_captcha)
    db.session.commit()
    return jsonify({"code":200,"message":"发送成功"})




